package com.koron.sinoprobe.web.plan.excel;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.koron.bean.base.Response;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.staff.StaffBean;
import com.koron.common.core.business.common.mapper.StaffMapper;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.sinoprobe.web.ledger.bean.entity.SpProject;
import com.koron.sinoprobe.web.ledger.service.SpProjectService;
import com.koron.sinoprobe.web.plan.bean.entity.SpPlan;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jzp
 * @since 2022/8/9
 */
public class SpPlanPackageListener extends AnalysisEventListener<SpPlan> {
    private String errorMessage;

    // 部门缓存
    private final Map<String, String> deptCache = new HashMap<>();
    // 人员缓存
    private final Map<String, String> staffCache = new HashMap<>();

    private final SpProjectService projectService;
    private final List<SpProject> result = new ArrayList<>();

    public SpPlanPackageListener(SpProjectService projectService) {
        this.projectService = projectService;
    }

    @Override
    public void invoke(SpPlan data, AnalysisContext context) {
        // 设置部门信息
        data.setHostDeptId(getDeptIdByName(data.getHostDeptName()));
        if (StrUtil.isNotEmpty(data.getHostOrgName())) {
            data.setHostOrgId(getDeptIdByName(data.getHostOrgName()));
        }

        // 设置人员信息
        data.setLeader(getStaffAccountByName(data.getLeaderName()));
        result.add(BeanUtil.toBean(data, SpProject.class));
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (result.isEmpty()) {
            return;
        }
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), projectService, "saveOrUpdateBatch", Boolean.class, result);
    }

    // 根据部门名称获取id
    public String getDeptIdByName(String name) {
        if (deptCache.containsKey(name)) {
            return deptCache.get(name);
        }
        OrgBean orgBean = new OrgBean();
        orgBean.setName(name);
        orgBean.setAppid(ThreadLocalContext.get().getAppId());
        String [] split = null;
        if (name != null && name.contains("|")) {
            split = name.split("\\|", 2);
            if (split.length == 2) {
                orgBean.setName(split[0]);
                orgBean.setId(split[1]);
            }
        }

        try (SessionFactory factory = new SessionFactory()) {
            StaffMapper mapper = factory.getMapper(StaffMapper.class);
            List<OrgBean> orgBeans = mapper.selectOrgList(orgBean);
            // 部门不存在
            if (orgBeans == null || orgBeans.size() == 0) {
                deptCache.put(name, null);
                errorMessage += "部门不存在:" + name + "; ";
                return null;
            } else if (orgBeans.size() > 1) {
                // 同名部门
                deptCache.put(name, "");
                errorMessage += "同名部门:" + name + "; ";
                return "";
            }
            deptCache.put(name, orgBeans.get(0).getId());
            return orgBeans.get(0).getId();
        }
    }

    // 根据姓名获取账号
    public String getStaffAccountByName(String name) {
        if (staffCache.containsKey(name)) {
            return staffCache.get(name);
        }
        StaffBean staffBean = new StaffBean();
        staffBean.setName(name);
        staffBean.setAppId(ThreadLocalContext.get().getAppId());
        String[] split = null;
        if (name != null && name.contains("|")) {
            split = name.split("\\|", 2);
            if (split.length == 2) {
                staffBean.setName(split[0]);
                staffBean.setId(split[1]);
            }
        }
        try (SessionFactory factory = new SessionFactory()) {
            StaffMapper mapper = factory.getMapper(StaffMapper.class);
            List<StaffBean> staffBeans = mapper.selectList(staffBean);
            // 用户不存在
            if (staffBeans == null || staffBeans.size() == 0) {
                staffCache.put(name, null);
                errorMessage += "用户不存在:" + name + "; ";
                return null;
            } else if (staffBeans.size() > 1) {
                // 同名用户
                staffCache.put(name, "");
                errorMessage += "同名用户:" + name + "; ";
                return "";
            }
            staffCache.put(name, staffBeans.get(0).getAccount());
            return staffBeans.get(0).getAccount();
        }
    }

    public Response<String> getSheetResponse() {
        if (StringUtils.isEmpty(errorMessage)) {
            return Response.ok("导入成功");
        }
        Response<String> response = new Response<>();
        response.setCode(5001);
        response.setDescription(errorMessage);
        response.setData(errorMessage);
        return response;
    }

}
